package com.dragon.user.util;

import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class JWTUtil {
    // 一周
    private static final long EXPIRE_TIME = 7 * 24 * 60 * 60 * 1000;

    public static final String HEADER_USERID = "userId";

    public static final String TOKEN_PREFIX = "Bearer";
    /**
     * jwt 密钥
     */
    private static final String SECRET = "jwt_secret";

    /**
     * 根据用户ID生成token
     *
     * @param userId
     * @return
     */
    public static String sign(String userId) {
        LocalDateTime now = LocalDateTime.now();
        HashMap<String, Object> map = new HashMap<>();
        map.put(HEADER_USERID, userId);
        String jwt = Jwts.builder().setSubject(HEADER_USERID).setClaims(map)
                .setExpiration(Date.from(now.atZone(ZoneId.systemDefault()).toInstant()))
                .signWith(SignatureAlgorithm.HS512, SECRET)
                .compact();

        return TOKEN_PREFIX + " " + jwt;
    }

    /**
     * 通过token 获取用户id
     *
     * @param token
     * @return
     */
    public static String getUnionIdByToken(String token) {
        try {
            Map<String, Object> tokenBody = Jwts.parser()
                    .setSigningKey(SECRET)
                    .parseClaimsJws(token.replace(TOKEN_PREFIX, ""))
                    .getBody();
            String userId = String.valueOf(tokenBody.get(HEADER_USERID));
            if (StringUtils.isEmpty(userId)) {
                userId = "";
            }
            return userId;
        } catch (ExpiredJwtException e) {
            log.error("token 解析异常:", e);
            e.printStackTrace();
        }
        return null;
    }
}
